package com.example.mcu_up.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import com.example.mcu.serial.SerialSend;
import com.example.mcu_up.Boot;
import com.example.mcu_up.R;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;



public class ConfirmDialog extends Dialog {
	
	


	private Context context;
	private TextView titleTv,contentTv;
	private View okBtn,cancelBtn;
	private OnDialogClickListener dialogClickListener;
	 private ProgressBar mProgress;
	    private Dialog mDownloadDialog;
	    private HashMap<String, String> mHashMap=null;
	    private downloadApkThread thread=null;
	    private static boolean isTrue=false;
		static File mcufile=null;
		  private  boolean cancelUpdate = false;
	    /* 下载中 */
	    private static final int DOWNLOAD = 1;
	    /* 下载结束 */
	    private static final int DOWNLOAD_FINISH = 2;
	    
	    /* 下载保存路径 */
	    private String mSavePath;
	    /* 记录进度条数量 */
	    private int progress;
	    
	    public ConfirmDialog(Context context, int theme,HashMap<String, String> map) {
			super(context, theme);
			this.context = context;
			mHashMap=map;
			initalize();
			// TODO Auto-generated constructor stub
		}
	    
	    
	/*public ConfirmDialog(Context context,HashMap<String, String> map) {
		super(context);
		this.context = context;
		mHashMap=map;
		initalize();
	}*/
	
		private Handler mHandler = new Handler()
		    {
		        public void handleMessage(Message msg)
		        {
		            switch (msg.what)
		            {
		            // 正在下载
		            case DOWNLOAD:
		                // 设置进度条位置
		            	 
		                mProgress.setProgress(progress);
		                break;
		            case DOWNLOAD_FINISH:
		             // Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_LONG).show();
		            	if(isTrue){
		            		 thread.interrupt();
		            		 thread=null;
	                      isTrue=false;
		            	}
		            	 Intent intent=new Intent(context,Boot.class);
		            	  intent.putExtra("path", mcufile.getAbsolutePath());
		            	  context.startActivity(intent);
		            	  SerialSend.getInstance().sendStatus(SerialSend.Serial_BOOTLOADER);
		            	 // SerialSend.getInstance().sendStatus(SerialSend.Serial_HARDWAREVERSION);
		            	  Toast.makeText(context, "下载完成", Toast.LENGTH_LONG).show();
		              //  SerialSend.getInstance().sendStatus(SerialSend.Serial_BOOTLOADER);
		             // byte[][][] code=MCU_Reader.toAll(mcufile.getAbsolutePath());
		             // Manager.getInstance(MainActivity.this).setCodes(code);
		             
		              
		             /* if(code!=null){
		            	 for(int i=0;i<code.length;i++)
		            	    for(int j=0;j<code[i].length;j++)
		            	 	   Toast.makeText(MainActivity.this, ""+byteToString(code[i][j]), Toast.LENGTH_LONG).show();
		            	  
		              }*/
		                break;
		                
		                
		                
		            default:
		                break;
		            }
		        };
		    };
	private void initalize() {
		LayoutInflater inflater = LayoutInflater.from(context);
		View view = inflater.inflate(R.layout.confirm_dialog, null);
		setContentView(view);
		initWindow();

		titleTv = (TextView) findViewById(R.id.title_name);
		contentTv = (TextView) findViewById(R.id.text_view);
		okBtn = findViewById(R.id.btn_ok);
		cancelBtn = findViewById(R.id.btn_cancel);
		okBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dismiss();
				showDownloadDialog();
				if(dialogClickListener != null){
					dialogClickListener.onOKClick();
				}
			}
		});
		cancelBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dismiss();
				if(dialogClickListener != null){
					dialogClickListener.onCancelClick();
				}
			}
		});
	}

	private void initWindow() {
		Window dialogWindow = getWindow();
		dialogWindow.setBackgroundDrawable(new ColorDrawable(0));
		dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		DisplayMetrics d = context.getResources().getDisplayMetrics();
		lp.width = (int) (d.widthPixels * 0.7); 
		lp.y=90;
		lp.height=220;
		lp.gravity = Gravity.CENTER;		
		dialogWindow.setAttributes(lp);
	}
	
	public void setOnDialogClickListener(OnDialogClickListener clickListener){
		dialogClickListener = clickListener;
	}
	
	
	public interface OnDialogClickListener{
		void onOKClick();
		void onCancelClick();
	}
	  /**
     * 下载文件线程
     * 
     * @author coolszy
     *@date 2012-4-26
     *@blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread
    {
        @Override
        public void run()
        {
            try
            {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";
                    
                    URL url = new URL(mHashMap.get("url"));
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists())
                    {
                        file.mkdir();
                    }
                     mcufile= new File(mSavePath,mHashMap.get("url").substring(mHashMap.get("url").lastIndexOf("/")+1));
                    FileOutputStream fos = new FileOutputStream(mcufile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do
                    {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread<=0)
                        {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                        try {
							sleep(100);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e)
            {
                e.printStackTrace();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
            
            // 取消下载对话框显示
            mDownloadDialog.dismiss();
        }
    };
    
    
    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog()
    {
      /*  // 构造软件下载对话框
        AlertDialog.Builder builder = new Builder(this);
        builder.setTitle(R.string.s_update);
        // 给下载对话框增加进度条
        final LayoutInflater inflater = LayoutInflater.from(this);
        View v = inflater.inflate(R.layout.mcu_progress, null);
        
        mProgress = (ProgressBar) v.findViewById(R.id.progress);
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton(R.string.s_cancel, new OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
                // 设置取消状态
                cancelUpdate = true;
            }
        });
        mDownloadDialog = builder.create();
        mDownloadDialog.show();*/
        
    	  // 给下载对话框增加进度条
        final LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.mcu_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.progress);
       
     Button   cancel=(Button)v.findViewById(R.id.cancel);
       
        mDownloadDialog =new Dialog(context, R.style.Dialog_Fullscreen); 
        @SuppressWarnings("deprecation")
		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); 
        mDownloadDialog.addContentView(v, params); 

        Window dialogWindow = mDownloadDialog.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
		dialogWindow.setGravity(Gravity.CENTER | Gravity.BOTTOM);
		//显示的坐标
		lp.x = 0;
		lp.y = 1;
		//int width = context1.getResources().getDimensionPixelOffset(R.dimen.d_width);
		//int height = context1.getResources().getDimensionPixelOffset(R.dimen.d_height);
		//dialog的大小
		lp.width = 320;
		


		dialogWindow.setAttributes(lp);
        
        
        
        mDownloadDialog.show();
        cancel.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				mDownloadDialog.dismiss();
				 //  deleteFile(new File("/cache/update.zip"));
                  // new FileService(mContext).delete(url);
                   //HttpUtil.start(mContext);
				   cancelUpdate = true;
			}
		});
      
        
        if(thread==null){

        	  thread=new downloadApkThread();
              isTrue=true;
              thread.start();
      }
  }
    
}
